<template>
  <el-dialog
    :title="id ? $t('common.modify') : $t('common.add')"
    :visible.sync="dialogVisible"
    width="800px"
    :show="show"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="open"
  >
    <el-form
      ref="form"
      :model="info"
      label-width="120px"
      :rules="rules"
      v-loading="infoLoading"
    >
      <div class="el-dialog-div form-scrollbar">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('customer.customerName')" prop="name">
              <el-input
                type="text"
                v-model="info.name"
                :placeholder="$t('common.enter', [$t('customer.customerName')])"
                maxlength="255"
              />
            </el-form-item>
            <el-form-item :label="$t('customer.phone')">
              <el-input
                type="text"
                v-model="info.mobile"
                :placeholder="
                  $t('common.enter', [$t('customer.customerPhone')])
                "
                maxlength="255"
              />
            </el-form-item>
            <el-form-item :label="$t('common.email')" prop="email">
              <el-input
                type="text"
                v-model="info.email"
                :placeholder="
                  $t('common.enter', [$t('customer.customerEmail')])
                "
                maxlength="255"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('customer.office')">
              <el-input
                type="text"
                v-model="info.jobTitle"
                :placeholder="
                  $t('common.enter', [$t('customer.customerJobTitle')])
                "
                maxlength="255"
              />
            </el-form-item>
            <el-form-item :label="$t('customer.companyPhone')">
              <el-input
                type="text"
                v-model="info.companyTel"
                :placeholder="$t('customer.companyPhone')"
                maxlength="255"
              />
            </el-form-item>
            <el-form-item :label="$t('customer.linkinUrl')">
              <el-input
                type="text"
                v-model="info.linkedinUrl"
                :placeholder="$t('customer.linkinUrl')"
                maxlength="255"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('common.type')" prop="type">
              <el-select
                :disabled="Boolean(this.id)"
                v-model="info.type"
                class="filter-left"
                :placeholder="$t('common.type')"
                clearable
                filterable
                size="small"
              >
                <el-option
                  v-for="item in typeOptions"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('common.source')">
              <el-select
                v-model="info.sourceId"
                class="filter-left"
                :placeholder="$t('common.source')"
                clearable
                filterable
                size="small"
              >
                <el-option
                  v-for="item in sourceOptions"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('common.grouping')">
              <el-select
                v-model="info.groupId"
                class="filter-left"
                :placeholder="$t('common.grouping')"
                clearable
                filterable
                size="small"
              >
                <el-option
                  v-for="item in groupOptions"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item :label="$t('common.remark')">
          <el-input type="textarea" v-model="info.remarks" :rows="6"></el-input>
        </el-form-item>
        <el-form-item :label="$t('customer.attention')">
          <el-rate
            style="line-height: 2.4"
            v-model="info.attention"
            :colors="colors"
          >
          </el-rate>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-row>
        <el-col :span="12" class="btnEdit">
          <el-button
            :disabled="infoLoading"
            type="primary"
            @click="subInfo()"
            >{{ $t('common.save') }}</el-button
          >
        </el-col>
        <el-col :span="12" class="btnEdit">
          <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import { createCustomer, getCustomer, updateCustomer } from '@/api/customer'
import { getSourceCollect } from '@/api/customer/source'
import { getGroupCollect } from '@/api/customer/group'

export default {
  name: 'edit',
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    id: '',
    blockId: '',
    closeAction: '',
    origin: {
      type: Number,
      default: 1,
    },
  },
  data() {
    let checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
      if (!value) {
        return callback(new Error(this.$t('customer.phoneNumberCantBeEmpty')))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error(this.$t('customer.enterNumberic')))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error(this.$t('customer.phoneNumberFormatError')))
          }
        }
      }, 100)
    }
    let checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error(this.$t('customer.emailCantbeEmpty')))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error(this.$t('customer.invalidEmailFormat')))
        }
      }, 100)
    }
    return {
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      info: {},
      tempData: {
        name: '',
        mobile: '',
        email: '',
        linkedinUrl: '',
        sourceId: '',
        groupId: '',
        type: '',
        jobTitle: '',
        companyTel: '',
        attention: 0,
        remarks: '',
        isIntention: 0,
      },
      typeOptions: [
        { label: this.$t('route.dataSearch'), value: 1 },
        { label: this.$t('customer.dataMarketing'), value: 2 },
        { label: this.$t('customer.externalImport'), value: 3 },
      ],
      sourceOptions: [],
      groupOptions: [],
      dialogVisible: this.show,
      infoLoading: false,
      isChange: false,
      initForm: false,
      rules: {
        name: [
          {
            required: true,
            message: this.$t('common.enter', [
              this.$t('customer.customerName'),
            ]),
            trigger: 'blur',
          },
        ],
        mobile: [{ required: true, validator: checkPhone, trigger: 'blur' }],
        email: [{ required: true, validator: checkEmail, trigger: 'blur' }],
        type: [
          {
            required: true,
            message: this.$t('common.select', [this.$t('common.type')]),
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    async open() {
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      this.infoLoading = true
      if (this.id != '') {
        const { data } = await getCustomer(this.id)
        if (data.groupId == 0) {
          data.groupId = ''
        }
        if (data.sourceId == 0) {
          data.sourceId = ''
        }
        this.info = data
      } else {
        this.resetTempData()
        this.info = this.tempData
      }
      this.initForm = true
      //获取来源
      await getSourceCollect().then((res) => {
        this.sourceOptions = res.data
      })
      //获取分组
      await getGroupCollect().then((res) => {
        this.groupOptions = res.data
      })
      setTimeout(() => {
        this.infoLoading = false
      }, 0.5 * 1000)
    },
    handleClose(done) {
      if (this.isChange) {
        this.$confirm(
          this.$t('common.unsavedChangesTip'),
          this.$t('common.tips'),
          {
            type: 'warning',
          }
        )
          .then((_) => {
            this.$emit('update:show', false)
          })
          .catch((_) => {})
      } else {
        this.$emit('update:show', false)
      }
    },
    resetTempData() {
      this.tempData = {
        name: '',
        mobile: '',
        email: '',
        linkedinUrl: '',
        sourceId: '',
        groupId: '',
        type: '',
        company: '',
        jobTitle: '',
        companyTel: '',
        attention: 0,
        remarks: '',
        isIntention: 0,
      }
    },
    subInfo() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          this.infoLoading = true
          let data = this.info
          if (data.groupId == '') {
            data.groupId = 0
          }
          if (data.sourceId == '') {
            data.sourceId = 0
          }
          data.origin = this.origin
          data.blockId = this.blockId
          if (this.id != '') {
            await updateCustomer(this.id, data)
              .then((res) => {
                this.$notify({
                  title: this.$t('common.success'),
                  message: this.$t('common.updateSuccessfully'),
                  type: 'success',
                  duration: 2000,
                })
                this.$emit('closeAction')
              })
              .catch(() => {
                setTimeout(() => {
                  this.infoLoading = false
                }, 0.5 * 1000)
              })
          } else {
            await createCustomer(data)
              .then((res) => {
                this.$notify({
                  title: this.$t('common.success'),
                  message: this.$t('common.addSuccessfully'),
                  type: 'success',
                  duration: 2000,
                })
                this.$emit('closeAction')
              })
              .catch(() => {
                setTimeout(() => {
                  this.infoLoading = false
                }, 0.5 * 1000)
              })
          }
        }
      })
    },
  },
  watch: {
    show() {
      this.dialogVisible = this.show
    },
    tempData: {
      handler: function () {
        if (this.initForm) {
          this.isChange = false
          this.initForm = false
        } else {
          this.isChange = true
        }
      },
      deep: true,
    },
  },
}
</script>

<style scoped>
.form-scrollbar {
  height: 450px !important;
}

/deep/ textarea {
  resize: none;
}
</style>
